Compare commits

...

2 Commits

Author SHA1 Message Date
a9b388fe4b
hru(1): adds more descriptive comments 2024-07-13 18:18:32 -06:00
e4e823a309
fop(1): adds more comments 2024-07-13 18:03:49 -06:00
2 changed files with 49 additions and 29 deletions

View File

@ -32,8 +32,8 @@ use sysexits::{ EX_DATAERR, EX_IOERR, EX_UNAVAILABLE, EX_USAGE };
fn main() {
let argv = args().collect::<Vec<String>>();
let mut d = '\u{1E}'.to_string();
let mut index_arg = 0;
let mut d = '\u{1E}'.to_string(); /* ASCII record separator */
let mut optind = 0;
let usage = format!(
"Usage: {} [-d delimiter] index command [args...]",
@ -43,10 +43,9 @@ fn main() {
while let Some(opt) = argv.getopt("d:") {
match opt.opt() {
Ok(_) => {
/* unwrap because Err(OptError::MissingArg) will be returned if
* opt.arg() is None */
/* delimiter */
d = opt.arg().unwrap();
index_arg = opt.ind();
optind = opt.ind();
},
Err(_) => {
eprintln!("{}", usage);
@ -55,38 +54,46 @@ fn main() {
};
}
let command_arg = index_arg as usize + 1;
/* index of the argv[0] for the operator command */
let command_arg = optind as usize + 1;
argv.get(command_arg).unwrap_or_else(|| {
/* argv[0] of the operator command */
let operator = argv.get(command_arg).unwrap_or_else(|| {
eprintln!("{}", usage);
exit(EX_USAGE);
});
let index = argv[index_arg].parse::<usize>().unwrap_or_else(|e| {
/* parse the specified index as a number we can use */
let index = argv[optind].parse::<usize>().unwrap_or_else(|e| {
eprintln!("{}: {}: {}", argv[0], argv[1], e);
exit(EX_DATAERR);
});
let mut buf = String::new();
let _ = stdin().read_to_string(&mut buf);
/* split the buffer by the delimiter (by default, '\u{1E}') */
let mut fields = buf.split(&d).collect::<Vec<&str>>();
/* collect arguments for the operator command */
let opts = argv
.iter()
.clone()
.skip(command_arg + 1)
.skip(command_arg + 1) /* skip the command name */
.collect::<Vec<&String>>();
let mut spawned = Command::new(argv.get(command_arg).unwrap())
.args(opts)
/* spawn the command to operate on the field */
let mut spawned = Command::new(operator)
.args(opts) /* spawn with the specified arguments */
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stdout(Stdio::piped()) /* piped stdout to handle output ourselves */
.spawn()
.unwrap_or_else( |e| {
eprintln!("{}: {}: {}", argv[0], argv[command_arg], e.strerror());
exit(EX_UNAVAILABLE);
});
/* get field we want to pipe into spawned program */
let field = fields.get(index).unwrap_or_else(|| {
eprintln!(
"{}: {}: No such index in input",
@ -96,9 +103,10 @@ fn main() {
exit(EX_DATAERR);
});
/* get the stdin of the newly spawned program and feed it the field val */
if let Some(mut child_stdin) = spawned.stdin.take() {
let _ = child_stdin.write_all(field.as_bytes());
drop(child_stdin);
drop(child_stdin); /* stay safe! drop your children! */
}
let output = spawned.wait_with_output().unwrap_or_else(|e| {
@ -106,17 +114,22 @@ fn main() {
exit(EX_IOERR);
});
/* get the output with which the original field will be replaced */
let mut replace = output.stdout.clone();
/* as long as its not a newline, set the replacement to the output */
if replace.pop() != Some(b'\n') { replace = output.stdout; }
/* convert the output of the program to UTF-8 */
let new_field = String::from_utf8(replace).unwrap_or_else(|e| {
eprintln!("{}: {}: {}", argv[0], argv[command_arg], e);
exit(EX_IOERR);
});
/* store the new field in the old fields vector */
fields[index] = &new_field;
/* fop it */
stdout().write_all(
fields.join(&d.to_string()).as_bytes()
).unwrap_or_else(|e| {

View File

@ -29,40 +29,45 @@ extern crate sysexits;
use strerror::StrError;
use sysexits::{ EX_DATAERR, EX_IOERR, EX_SOFTWARE };
/* list of SI prefixes */
const LIST: [(u32, &str); 10] = [
(3, "k"),
(6, "M"),
(9, "G"),
(12, "T"),
(15, "P"),
(18, "E"),
(21, "Z"),
(24, "Y"),
(27, "R"),
(30, "Q")
(3, "k"), /* kilo */
(6, "M"), /* mega */
(9, "G"), /* giga */
(12, "T"), /* tera */
(15, "P"), /* peta */
(18, "E"), /* exa */
(21, "Z"), /* zetta */
(24, "Y"), /* yotta */
(27, "R"), /* ronna */
(30, "Q"), /* quetta */
];
fn convert(input: u128) -> Result<(f64, (u32, &'static str)), String> {
/* preserve decimal places in output by casting to a float */
let mut out = (input as f64, (0_u32, ""));
let mut out = (input as f64, (0_u32, ""));
if input < 1000 { return Ok(out); }
if input < 1000 { return Ok(out); } /* too low to convert */
for (n, p) in LIST {
let c = match 10_u128.checked_pow(n) {
Some(c) => c,
None => {
None => { /* too big for the laws of computing :( */
return Err(format!("10^{}: Integer overflow", n.to_string()));
},
};
match c.cmp(&input) {
Ordering::Less => {
Ordering::Less => { /* c < input */
/* the program will keep assigning out every loop until either
* the list runs out of higher prefix bases or the input is
* greater than the prefix base */
out = (input as f64 / c as f64, (n, p));
},
Ordering::Equal => {
Ordering::Equal => { /* c == input */
return Ok((input as f64 / c as f64, (n, p)));
},
Ordering::Greater => {},
Ordering::Greater => {}, /* c > input */
};
}
@ -72,6 +77,7 @@ fn convert(input: u128) -> Result<(f64, (u32, &'static str)), String> {
fn main() -> ExitCode {
let argv = args().collect::<Vec<String>>();
let mut buf = String::new();
while let Ok(_) = stdin().read_line(&mut buf) {
if buf.is_empty() { return ExitCode::SUCCESS; }
@ -96,6 +102,7 @@ fn main() -> ExitCode {
let si_prefix = format!("{}B", prefix.1);
/* round output number to one decimal place */
let out = ((number * 10.0).round() / 10.0).to_string();
stdout().write_all(format!("{} {}\n", out, si_prefix).as_bytes())