use std::fmt;
use std::process::Stdio;
use std::sync::Arc;
use std::time::Instant;
use crate::LineQueue;
#[cfg(test)]
mod tests;
const SLACK: usize = 8 * 1024;
#[derive(Clone, Debug, Default)]
pub struct Capture(Kind);
#[derive(Clone, Debug, Default)]
enum Kind {
#[default]
Discard,
Inherit,
Whole(WholeCapture),
Tail {
limit: usize,
},
Lines(LineCapture),
}
#[derive(Clone, Debug)]
#[must_use]
pub struct WholeCapture {
limit: usize,
over: OverLimit,
}
#[derive(Clone, Debug)]
#[must_use]
pub struct LineCapture {
queue: LineQueue,
line: usize,
total: usize,
over: OverLimit,
long: LongLine,
end: u8,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum LongLine {
#[default]
Over,
Skip,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum OverLimit {
#[default]
Stop,
Sink,
}
impl Capture {
#[must_use]
pub const fn discard() -> Self {
Self(Kind::Discard)
}
#[must_use]
pub const fn inherit() -> Self {
Self(Kind::Inherit)
}
#[must_use]
pub const fn tail(limit: usize) -> Self {
Self(Kind::Tail { limit })
}
pub const fn whole(limit: usize) -> WholeCapture {
WholeCapture {
limit,
over: OverLimit::Stop,
}
}
pub const fn lines(queue: LineQueue, total: usize) -> LineCapture {
LineCapture {
queue,
line: usize::MAX,
total,
over: OverLimit::Stop,
long: LongLine::Over,
end: b'\n',
}
}
pub(super) fn stdio(&self) -> Stdio {
match self.0 {
Kind::Discard => Stdio::null(),
Kind::Inherit => Stdio::inherit(),
Kind::Whole(_) | Kind::Tail { .. } | Kind::Lines(_) => Stdio::piped(),
}
}
pub(super) const fn inherits(&self) -> bool {
matches!(self.0, Kind::Inherit)
}
const fn queue(&self) -> Option<&LineQueue> {
match &self.0 {
Kind::Lines(lines) => Some(&lines.queue),
_ => None,
}
}
pub(super) fn stopping(&self) {
if let Some(queue) = self.queue() {
queue.stopping();
}
}
pub(super) fn drain_until(&self, deadline: Instant) {
if let Some(queue) = self.queue() {
queue.drain_until(deadline);
}
}
pub(super) fn end(&self) {
if let Some(queue) = self.queue() {
queue.end();
}
}
}
impl WholeCapture {
pub const fn over(mut self, over: OverLimit) -> Self {
self.over = over;
self
}
}
impl From<WholeCapture> for Capture {
fn from(whole: WholeCapture) -> Self {
Self(Kind::Whole(whole))
}
}
impl LineCapture {
pub const fn line(mut self, line: usize) -> Self {
self.line = line;
self
}
pub const fn long(mut self, long: LongLine) -> Self {
self.long = long;
self
}
pub const fn over(mut self, over: OverLimit) -> Self {
self.over = over;
self
}
pub const fn end(mut self, end: u8) -> Self {
self.end = end;
self
}
}
impl From<LineCapture> for Capture {
fn from(lines: LineCapture) -> Self {
Self(Kind::Lines(lines))
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Captured {
bytes: Vec<u8>,
over_limit: bool,
long_line: bool,
}
impl Captured {
#[must_use]
pub fn bytes(&self) -> &[u8] {
&self.bytes
}
#[must_use]
pub fn into_bytes(self) -> Vec<u8> {
self.bytes
}
#[must_use]
pub const fn over_limit(&self) -> bool {
self.over_limit
}
#[must_use]
pub const fn long_line(&self) -> bool {
self.long_line
}
}
#[derive(Clone)]
pub(super) struct OutputCopy(Arc<CopyFn>);
type CopyFn = dyn Fn(&[u8]) + Send + Sync;
impl OutputCopy {
pub(super) fn new(copy: impl Fn(&[u8]) + Send + Sync + 'static) -> Self {
Self(Arc::new(copy))
}
pub(super) fn send(&self, chunk: &[u8]) {
(self.0)(chunk);
}
}
impl fmt::Debug for OutputCopy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("OutputCopy(..)")
}
}
#[derive(Debug)]
pub(super) struct Keeper {
capture: Capture,
kept: Captured,
line: Vec<u8>,
read: usize,
listening: bool,
skipping: bool,
}
impl Keeper {
pub(super) fn new(capture: &Capture) -> Self {
Self {
capture: capture.clone(),
kept: Captured::default(),
line: Vec::new(),
read: 0,
listening: true,
skipping: false,
}
}
pub(super) fn add(&mut self, bytes: &[u8]) -> bool {
let kept = &mut self.kept;
match self.capture.0 {
Kind::Discard | Kind::Inherit => false,
Kind::Lines(LineCapture {
line,
total,
over,
long,
end,
..
}) => self.add_lines(bytes, line, total, long, end) && over == OverLimit::Stop,
Kind::Whole(WholeCapture { limit, over }) => {
let room = limit.saturating_sub(kept.bytes.len());
kept.bytes
.extend_from_slice(&bytes[..room.min(bytes.len())]);
if bytes.len() <= room || kept.over_limit {
return false;
}
kept.over_limit = true;
over == OverLimit::Stop
}
Kind::Tail { limit } => {
kept.bytes.extend_from_slice(bytes);
if kept.bytes.len() > limit.saturating_add(SLACK) {
kept.bytes.drain(..kept.bytes.len() - limit);
kept.over_limit = true;
}
false
}
}
}
fn add_lines(
&mut self,
bytes: &[u8],
line: usize,
total: usize,
long: LongLine,
end: u8,
) -> bool {
if self.kept.over_limit {
return false;
}
let mut rest = bytes;
loop {
let (piece, ended) = match rest.iter().position(|byte| *byte == end) {
Some(at) => (&rest[..at], true),
None => (rest, false),
};
self.read = self.read.saturating_add(piece.len() + usize::from(ended));
if !self.skipping {
self.line.extend_from_slice(piece);
}
let over_line = self.line.len() > line;
if self.read > total || (over_line && long == LongLine::Over) {
self.kept.over_limit = true;
self.kept.long_line |= over_line && self.read <= total;
self.line = Vec::new();
return true;
}
if over_line {
self.skipping = true;
self.kept.long_line = true;
self.line = Vec::new();
}
if !ended {
return false;
}
if self.skipping {
self.skipping = false;
} else {
self.push_line();
}
rest = &rest[piece.len() + 1..];
if rest.is_empty() {
return false;
}
}
}
fn push_line(&mut self) {
let line = std::mem::take(&mut self.line);
if let Some(queue) = self.capture.queue()
&& self.listening
{
self.listening = queue.push(line);
}
}
pub(super) fn finish(mut self) -> Captured {
if self.capture.queue().is_some() && !self.kept.over_limit && !self.line.is_empty() {
self.push_line();
}
if let Kind::Tail { limit } = self.capture.0
&& self.kept.bytes.len() > limit
{
self.kept.bytes.drain(..self.kept.bytes.len() - limit);
self.kept.over_limit = true;
}
self.kept
}
}