Expand description
§Stdio-Override
This crate provides a library for overriding Stdio streams.
It provides a guard for the replacement so that when the guard is dropped the streams are switched back
and the replacement stream will be closed.
You can create multiple stdio overrides, but if you attempt to drop them out of order then they will panic.
You can use the os_pipe
crate to capture the standard streams in
memory.
Notice: When trying to use this in tests you must run with cargo test -- --test-threads=1 --nocapture
otherwise it will redirect stdout/stderr again.
This library is made to be intuitive and easy to use.
§Examples
Stdout:
use stdio_override::StdoutOverride;
use std::fs;
let file_name = "./test.txt";
let guard = StdoutOverride::from_file(file_name)?;
println!("Isan to Stdout!");
let contents = fs::read_to_string(file_name)?;
assert_eq!("Isan to Stdout!\n", contents);
drop(guard);
println!("Outside!");
Stderr:
use stdio_override::StderrOverride;
use std::fs;
let file_name = "./testerr.txt";
let guard = StderrOverride::from_file(file_name)?;
eprintln!("Failure to stderr");
let contents = fs::read_to_string(file_name)?;
assert_eq!("Failure to stderr\n", contents);
drop(guard);
eprintln!("Stderr is back!");
Stdin:
use stdio_override::StdinOverride;
let file_name = "./inputs.txt";
fs::write(file_name, "Inputs to stdin")?;
let guard = StdinOverride::from_file(file_name)?;
let mut user_input = String::new();
io::stdin().read_line(&mut user_input)?;
drop(guard);
assert_eq!("Inputs to stdin", user_input);
// Stdin is working as usual again, because the guard is dropped.
Structs§
- Stderr
Override - An overridden standard error.
- Stdin
Override - An overridden standard input.
- Stdout
Override - An overridden standard output.