use std::collections::BTreeMap;
use std::io;
use std::process::ExitCode;
use std::fs::File;
use io::BufWriter;
use io::Write;
use io::BufRead;
use rs_ints2tinydict::Endian;
use rs_ints2tinydict::iowtr2wtr;
use rs_ints2tinydict::StrToInt;
use rs_ints2tinydict::str2int_default;
use rs_ints2tinydict::ints2dict2writer;
use rs_ints2tinydict::wtr2fn;
use rs_ints2tinydict::DictWriter;
const HELPMSG: &str = r#"
usage:
environment vars:
ENV_ENDIAN:
Lit => little endian
Big => little endian
ENV_OUTPUT_DICT_FILENAME:
The name of the dict to save.
Omit this and no file will be writen.
"#;
fn show_help() {
println!("{HELPMSG}");
}
struct Params {
show_help: bool,
}
impl Params {
fn from_args() -> Self {
let mut show_help: bool = false;
for arg in std::env::args_os() {
let o = arg.as_os_str();
let b: &[u8] = o.as_encoded_bytes();
match b {
b"-h" => show_help = true,
b"-help" => show_help = true,
b"--help" => show_help = true,
_ => {}
}
}
Self { show_help }
}
}
fn get_endian() -> impl Fn() -> Endian {
move || match std::env::var("ENV_ENDIAN").as_deref() {
Ok(s) => str::parse(s).unwrap_or(Endian::Lit),
Err(_) => Endian::Lit,
}
}
fn get_filename4dict() -> impl Fn() -> String {
move || std::env::var("ENV_OUTPUT_DICT_FILENAME").unwrap_or_default()
}
fn str2int() -> impl StrToInt {
str2int_default()
}
fn stdin2lines() -> impl Iterator<Item = Result<String, io::Error>> {
io::stdin().lock().lines()
}
fn sub() -> Result<(), io::Error> {
let p: Params = Params::from_args();
if p.show_help {
show_help();
return Ok(());
}
let lines = stdin2lines();
let s2i = str2int();
let ints = s2i.lines2ints(lines);
let end: Endian = get_endian()();
let output_filename: String = get_filename4dict()();
let ofile: Option<File> = File::create(output_filename).ok();
let o = io::stdout();
let mut ol = o.lock();
{
let mut bw = BufWriter::new(&mut ol);
let mut buf: BTreeMap<i32, u8> = BTreeMap::default();
let mapd_int_wtr = iowtr2wtr(&mut bw);
let dict: BTreeMap<u8, i32> = ints2dict2writer(ints, wtr2fn(mapd_int_wtr), &mut buf)?;
bw.flush()?;
if let Some(mut file) = ofile {
let obw = BufWriter::new(&mut file);
let mut dictwtr = end.wtr2dict_wtr(obw);
dictwtr.write(&dict)?;
drop(dictwtr);
file.flush()?;
file.sync_data()?;
}
}
ol.flush()
}
fn main() -> ExitCode {
sub().map(|_| ExitCode::SUCCESS).unwrap_or_else(|e| {
eprintln!("{e}");
ExitCode::FAILURE
})
}