Compare commits

..

No commits in common. "a9b388fe4b9101d8106064679cac6bfbe25a00c3" and "c7c6ca2c60d92e58fda3375c4a76ad0d051b2511" have entirely different histories.

2 changed files with 29 additions and 49 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(); /* ASCII record separator */
let mut optind = 0;
let mut d = '\u{1E}'.to_string();
let mut index_arg = 0;
let usage = format!(
"Usage: {} [-d delimiter] index command [args...]",
@ -43,9 +43,10 @@ fn main() {
while let Some(opt) = argv.getopt("d:") {
match opt.opt() {
Ok(_) => {
/* delimiter */
/* unwrap because Err(OptError::MissingArg) will be returned if
* opt.arg() is None */
d = opt.arg().unwrap();
optind = opt.ind();
index_arg = opt.ind();
},
Err(_) => {
eprintln!("{}", usage);
@ -54,46 +55,38 @@ fn main() {
};
}
/* index of the argv[0] for the operator command */
let command_arg = optind as usize + 1;
let command_arg = index_arg as usize + 1;
/* argv[0] of the operator command */
let operator = argv.get(command_arg).unwrap_or_else(|| {
argv.get(command_arg).unwrap_or_else(|| {
eprintln!("{}", usage);
exit(EX_USAGE);
});
/* parse the specified index as a number we can use */
let index = argv[optind].parse::<usize>().unwrap_or_else(|e| {
let index = argv[index_arg].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 the command name */
.skip(command_arg + 1)
.collect::<Vec<&String>>();
/* spawn the command to operate on the field */
let mut spawned = Command::new(operator)
.args(opts) /* spawn with the specified arguments */
let mut spawned = Command::new(argv.get(command_arg).unwrap())
.args(opts)
.stdin(Stdio::piped())
.stdout(Stdio::piped()) /* piped stdout to handle output ourselves */
.stdout(Stdio::piped())
.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",
@ -103,10 +96,9 @@ 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); /* stay safe! drop your children! */
drop(child_stdin);
}
let output = spawned.wait_with_output().unwrap_or_else(|e| {
@ -114,22 +106,17 @@ 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,45 +29,40 @@ 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"), /* 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 */
(3, "k"),
(6, "M"),
(9, "G"),
(12, "T"),
(15, "P"),
(18, "E"),
(21, "Z"),
(24, "Y"),
(27, "R"),
(30, "Q")
];
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, ""));
if input < 1000 { return Ok(out); } /* too low to convert */
let mut out = (input as f64, (0_u32, ""));
if input < 1000 { return Ok(out); }
for (n, p) in LIST {
let c = match 10_u128.checked_pow(n) {
Some(c) => c,
None => { /* too big for the laws of computing :( */
None => {
return Err(format!("10^{}: Integer overflow", n.to_string()));
},
};
match c.cmp(&input) {
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 */
Ordering::Less => {
out = (input as f64 / c as f64, (n, p));
},
Ordering::Equal => { /* c == input */
Ordering::Equal => {
return Ok((input as f64 / c as f64, (n, p)));
},
Ordering::Greater => {}, /* c > input */
Ordering::Greater => {},
};
}
@ -77,7 +72,6 @@ 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; }
@ -102,7 +96,6 @@ 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())