use std::future::Future;
use std::io;
use std::pin::Pin;
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
use tokio::process::{ChildStdin, ChildStdout};
use crate::DuplexTransport;
#[derive(Debug)]
pub struct StdioTransport {
pipes: PipeTransport<ChildStdin, ChildStdout>,
}
impl StdioTransport {
#[must_use]
pub fn new(stdin: ChildStdin, stdout: ChildStdout) -> Self {
Self {
pipes: PipeTransport::new(stdin, stdout),
}
}
}
impl DuplexTransport for StdioTransport {
fn read_chunk(
&mut self,
) -> Pin<Box<dyn Future<Output = io::Result<Option<String>>> + Send + '_>> {
self.pipes.read_chunk()
}
fn write(&mut self, frame: &str) -> Pin<Box<dyn Future<Output = io::Result<()>> + Send + '_>> {
self.pipes.write(frame)
}
}
#[derive(Debug)]
pub(crate) struct PipeTransport<W, R> {
stdin: W,
stdout: BufReader<R>,
held: Vec<u8>,
}
impl<W, R> PipeTransport<W, R>
where
W: AsyncWrite + Unpin + Send,
R: AsyncRead + Unpin + Send,
{
pub(crate) fn new(stdin: W, stdout: R) -> Self {
Self {
stdin,
stdout: BufReader::new(stdout),
held: Vec::new(),
}
}
}
impl<W, R> DuplexTransport for PipeTransport<W, R>
where
W: AsyncWrite + Unpin + Send,
R: AsyncRead + Unpin + Send,
{
fn read_chunk(
&mut self,
) -> Pin<Box<dyn Future<Output = io::Result<Option<String>>> + Send + '_>> {
Box::pin(async move {
loop {
let available = self.stdout.fill_buf().await?;
if available.is_empty() {
return if self.held.is_empty() {
Ok(None)
} else {
Err(io::Error::new(
io::ErrorKind::InvalidData,
"inbound stream ended inside a UTF-8 sequence",
))
};
}
let pulled = available.len();
self.held.extend_from_slice(available);
self.stdout.consume(pulled);
if let Some(chunk) = take_complete_utf8(&mut self.held)? {
return Ok(Some(chunk));
}
}
})
}
fn write(&mut self, frame: &str) -> Pin<Box<dyn Future<Output = io::Result<()>> + Send + '_>> {
let frame = frame.as_bytes().to_vec();
Box::pin(async move {
self.stdin.write_all(&frame).await?;
self.stdin.flush().await
})
}
}
fn take_complete_utf8(bytes: &mut Vec<u8>) -> io::Result<Option<String>> {
let complete = match std::str::from_utf8(bytes) {
Ok(_) => bytes.len(),
Err(error) if error.error_len().is_none() => error.valid_up_to(),
Err(error) => return Err(io::Error::new(io::ErrorKind::InvalidData, error)),
};
if complete == 0 {
return Ok(None);
}
let rest = bytes.split_off(complete);
let chunk = std::mem::replace(bytes, rest);
String::from_utf8(chunk)
.map(Some)
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
}