use crate::cmd::{Cmd, CmdInput, Pipeline};
use std::io::Read;
pub trait ReadExt: Read {
fn pipe(self, cmd: Cmd) -> Pipeline
where
Self: Sized + Send + 'static,
{
let mut pipeline = cmd.into_pipeline();
pipeline.input = Some(CmdInput::Reader(Box::new(self)));
pipeline
}
}
impl<R: Read> ReadExt for R {}
#[cfg(test)]
mod tests {
use super::*;
use crate::cmd;
use std::io::Cursor;
#[test]
fn test_read_ext_basic_pipe() -> Result<(), Box<dyn std::error::Error>> {
let data = Cursor::new(b"hello\nworld\n");
let result = data.pipe(cmd!("wc", "-l")).output()?;
assert_eq!(result.trim(), "2");
Ok(())
}
#[test]
fn test_read_ext_chained_pipe() -> Result<(), Box<dyn std::error::Error>> {
let data = Cursor::new(b"banana\napple\ncherry\n");
let result = data.pipe(cmd!("sort")).pipe(cmd!("head", "-1")).output()?;
assert_eq!(result.trim(), "apple");
Ok(())
}
#[test]
fn test_read_ext_with_empty_input() -> Result<(), Box<dyn std::error::Error>> {
let data = Cursor::new(b"");
let result = data.pipe(cmd!("wc", "-l")).output()?;
assert_eq!(result.trim(), "0");
Ok(())
}
#[test]
fn test_read_ext_binary_data() -> Result<(), Box<dyn std::error::Error>> {
let binary_data = vec![0u8, 1, 2, 3, 4, 5];
let data = Cursor::new(binary_data);
let result = data.pipe(cmd!("wc", "-c")).output()?;
assert_eq!(result.trim(), "6");
Ok(())
}
}