capture_stdio/pipe/
stdin.rs

1//! Intercept [std::io::Stdin]
2
3use super::PipedFd;
4use crate::Capture;
5use os_pipe::PipeWriter;
6use std::io::Error;
7
8/// Intercept stdin
9pub struct PipedStdin {
10    internal: PipedFd,
11}
12
13impl Capture for PipedStdin {
14    fn capture() -> Result<Self, Error> {
15        let internal = PipedFd::capture(0, true)?;
16        Ok(Self { internal })
17    }
18
19    fn restore(&mut self) {
20        self.internal.restore();
21    }
22}
23
24impl PipedStdin {
25    /// Get writer of pipe
26    pub fn get_writer(&mut self) -> &mut PipeWriter {
27        &mut self.internal.writer
28    }
29}
30
31#[cfg(test)]
32mod tests {
33    use crate::pipe::stdin::PipedStdin;
34    use crate::Capture;
35    use std::io::Write;
36
37    #[test]
38    fn test_stdin() {
39        let mut piped_stdin = PipedStdin::capture().unwrap();
40        let string = "Write something to stdin\n";
41        write!(piped_stdin.get_writer(), "{}", string).unwrap();
42
43        let mut line = String::new();
44        std::io::stdin().read_line(&mut line).unwrap();
45
46        assert_eq!(string, line);
47    }
48}