use std::io::{self, Read, Write};
use std::sync::OnceLock;
use std::time::{Duration, Instant};
use super::output::{Captured, Keeper};
use crate::sys::{self, Pipe};
const CHECK: Duration = Duration::from_millis(100);
const CHUNK: usize = 8 * 1024;
#[derive(Debug, Default)]
pub(super) struct Ends(OnceLock<Instant>);
impl Ends {
pub(super) fn set(&self, at: Instant) {
let _ = self.0.set(at);
}
fn at(&self) -> Option<Instant> {
self.0.get().copied()
}
fn ready(&self, pipe: impl Pipe + Copy, write: bool) -> io::Result<bool> {
loop {
let wait = match self.at() {
None => CHECK,
Some(at) => {
let left = at.saturating_duration_since(Instant::now());
if left.is_zero() {
return Ok(false);
}
left.min(CHECK)
}
};
if sys::ready(pipe, write, wait)? {
return Ok(true);
}
}
}
}
#[derive(Debug)]
pub(super) struct Kept {
pub(super) captured: Captured,
pub(super) first: Option<Instant>,
}
pub(super) fn read<P>(
mut pipe: P,
ends: &Ends,
mut keeper: Keeper,
over: impl Fn(),
) -> io::Result<Kept>
where
P: Read + Pipe,
{
let mut first = None;
let mut chunk = [0; CHUNK];
while ends.ready(&pipe, false)? {
let read = match pipe.read(&mut chunk) {
Ok(0) => break,
Ok(read) => read,
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
Err(error) => return Err(error),
};
first.get_or_insert_with(Instant::now);
if keeper.add(&chunk[..read]) {
over();
}
}
Ok(Kept {
captured: keeper.finish(),
first,
})
}
pub(super) fn write<P>(mut pipe: P, bytes: &[u8], ends: &Ends)
where
P: Write + Pipe,
{
if sys::unblock(&pipe).is_err() {
return;
}
let mut rest = bytes;
while !rest.is_empty() {
match ends.ready(&pipe, true) {
Ok(true) => {}
Ok(false) | Err(_) => return,
}
match pipe.write(rest) {
Ok(0) => return,
Ok(written) => rest = &rest[written..],
Err(error)
if matches!(
error.kind(),
io::ErrorKind::Interrupted | io::ErrorKind::WouldBlock
) => {}
Err(_) => return,
}
}
}