use std::io::Read;
pub fn read_bytes(in_path: Option<&str>) -> Result<Vec<u8>, String> {
match in_path {
Some(p) => std::fs::read(p).map_err(|e| format!("could not read {p:?}: {e}")),
None => {
let mut buf = Vec::new();
std::io::stdin()
.read_to_end(&mut buf)
.map_err(|e| format!("could not read stdin: {e}"))?;
Ok(buf)
}
}
}
pub fn read_text(in_path: Option<&str>) -> Result<String, String> {
String::from_utf8(read_bytes(in_path)?).map_err(|_| "input is not UTF-8".to_string())
}
pub fn take_in_flag(args: &[String]) -> Result<(Vec<String>, Option<String>), String> {
let mut rest = Vec::with_capacity(args.len());
let mut in_path = None;
let mut i = 0;
while i < args.len() {
if args[i] == "--in" {
let p = args
.get(i + 1)
.filter(|s| !s.is_empty())
.ok_or_else(|| "flag \"--in\" needs a value".to_string())?;
in_path = Some(p.clone());
i += 2;
continue;
}
rest.push(args[i].clone());
i += 1;
}
Ok((rest, in_path))
}
pub fn wants_help(args: &[String]) -> bool {
matches!(args.first().map(String::as_str), Some("--help" | "-h"))
}