1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
use bytesize::ByteSize;
use clap::{Arg, Command};
use std::io::{stdin, BufRead};

fn main() {
    let matches = Command::new("to-human-readable")
        .arg(Arg::new("bytes").required(false))
        .get_matches();

    if !matches.is_present("bytes") {
        let stdin = stdin().lock();
        for line in stdin.lines() {
            print_bytes(&line.unwrap());
        }
    } else {
        let bytes = matches.value_of("bytes").unwrap();
        print_bytes(bytes);
    };
}

fn print_bytes(str: &str) {
    let result = str.parse::<u64>();
    match result {
        Ok(bytes) => {
            println!(
                "{}  {}  {}",
                str,
                ByteSize(bytes).to_string_as(false),
                ByteSize(bytes).to_string_as(true)
            );
        }
        Err(_) => {
            println!("{}  ?  ?", str);
        }
    }
}