Last active
May 1, 2023 03:02
-
-
Save eblocha/8ad70f5a8bd7173011baccd43416279e to your computer and use it in GitHub Desktop.
Rust function to generify a file or stdin for command line apps. If a path is provided, it will return a readable file handle, or stdin if no path is provided.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::{fs, io, path::Path}; | |
fn file_or_stdin<P>(path: Option<P>) -> io::Result<Box<dyn io::Read + 'static>> | |
where | |
P: AsRef<Path>, | |
{ | |
match path { | |
None => Ok(Box::new(io::BufReader::new(io::stdin()))), | |
Some(path) => match fs::File::open(path) { | |
Ok(file) => Ok(Box::new(io::BufReader::new(file))), | |
Err(err) => { | |
return Err(err); | |
} | |
}, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment