quick_calc/
run.rs

1use crate::operations;
2
3pub fn run() -> Result<(), ()> {
4    // Define valid cli commands
5    let commands = ["format", "add", "sub", "mul", "div", "endian", "len", "bytelen", "charlen"];
6
7    // Grab useful cli args
8    let mut args = std::env::args().collect::<Vec<String>>();
9    args.remove(0);
10
11    // If no arguments are given, panic.
12    if args.is_empty() {
13        panic!("Give me some numbers to format");
14    }
15
16    // If an invliad command is given, panic.
17    if !args.iter().any(|x| commands.contains(&x.as_str())) {
18        panic!("Give me a valid command");
19    }
20
21    // If a valid command but no arguments are given, panic.
22    if args.iter().any(|x| commands.contains(&x.as_str())) && args.len() == 1 {
23        panic!("Give me some numbers to format");
24    }
25
26    match args.remove(0).as_str() {
27        "format"    => operations::format_args(&mut args),
28        "add"       => operations::calculate_operation(&mut args, |acc, x| acc + x),
29        "sub"       => operations::calculate_operation(&mut args, |acc, x| acc - x),
30        "mul"       => operations::calculate_operation(&mut args, |acc, x| acc * x),
31        "div"       => operations::calculate_operation(&mut args, |acc, x| acc / x),
32        "len" | "bytelen"   => operations::calculate_length(&mut args, true),
33        "charlen"   => operations::calculate_length(&mut args, false),
34        "endian"    => operations::swap_endianness(&mut args),
35        _           => panic!("Give me a valid command"),
36    };
37    Ok(())
38}