use dynamic dispatch to simplify file io a bit

This commit is contained in:
Connor Skees 2020-07-16 00:07:59 -04:00
parent d5d527ab70
commit fb724b8bee

View File

@ -192,28 +192,24 @@ fn main() -> std::io::Result<()> {
.unicode_error_messages(!matches.is_present("NO_UNICODE")) .unicode_error_messages(!matches.is_present("NO_UNICODE"))
.allows_charset(!matches.is_present("NO_CHARSET")); .allows_charset(!matches.is_present("NO_CHARSET"));
let (mut stdout_write, mut file_write);
let buf_out: &mut dyn Write = if let Some(path) = matches.value_of("OUTPUT") {
file_write = BufWriter::new(File::open(path).unwrap_or(File::create(path)?));
&mut file_write
} else {
stdout_write = BufWriter::new(stdout());
&mut stdout_write
};
if let Some(name) = matches.value_of("INPUT") { if let Some(name) = matches.value_of("INPUT") {
if let Some(path) = matches.value_of("OUTPUT") { buf_out.write_all(
let mut buf = BufWriter::new(File::open(path).unwrap_or(File::create(path)?)); from_path(name, &options)
buf.write_all( .unwrap_or_else(|e| {
from_path(name, &options) eprintln!("{}", e);
.unwrap_or_else(|e| { std::process::exit(1)
eprintln!("{}", e); })
std::process::exit(1) .as_bytes(),
}) )?;
.as_bytes(),
)?;
} else {
let mut stdout = BufWriter::new(stdout());
stdout.write_all(
from_path(name, &options)
.unwrap_or_else(|e| {
eprintln!("{}", e);
std::process::exit(1)
})
.as_bytes(),
)?;
}
} }
Ok(()) Ok(())
} }