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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
use bczhc_lib::utils::{get_args_without_self_path, get_file_name, MsgPrinter, MsgType};
use size_format::SizeFormatterBinary;

fn main() -> Result<(), String> {
    let msg_printer = MsgPrinter::new(format!(
        "Get file size.
Usage: {} [option] [--] <file-path>

Options:
-h, --human-readable  Print size as human-readable format.
--help  Show this help.",
        get_file_name()
    ));

    let args = get_args_without_self_path();

    if args.is_empty() {
        return msg_printer.show_msg(MsgType::Help);
    }

    if args.len() >= 4 {
        return msg_printer.show_msg(MsgType::InvalidArgumentCount(args.len()));
    }

    let mut arguments = Arguments {
        human_readable: false,
    };

    if args.len() == 1 {
        let argv = &args[0];
        if argv.starts_with('-') {
            // interpreted as an option
            match_option(&msg_printer, &mut arguments, argv)?;
        } else {
            // interpreted as file path positional argument
            return print_file_size(argv, arguments.human_readable);
        }
    }

    if args.len() == 2 {
        // (option) <file-path>
        // -- <file-path>
        return if args[0] == "--" {
            let file_path = &args[1];
            print_file_size(file_path, arguments.human_readable)
        } else {
            let option = &args[0];
            match_option(&msg_printer, &mut arguments, option)?;
            print_file_size(&args[1], arguments.human_readable)
        };
    }

    if args.len() == 3 {
        // (option) -- <file-path>
        if &args[1] != "--" {
            return Err(format!("Unknown parameter: {}", &args[1]));
        }
        let option = &args[0];
        let file_path = &args[2];

        match_option(&msg_printer, &mut arguments, option)?;
        return print_file_size(file_path, arguments.human_readable);
    }

    Ok(())
}

fn match_option(
    msg_printer: &MsgPrinter,
    arguments: &mut Arguments,
    option: &String,
) -> Result<(), String> {
    match option.as_str() {
        "-h" | "--human-readable" => {
            arguments.human_readable = true;
        }
        "--help" => {
            return msg_printer.show_msg(MsgType::Help);
        }
        _ => {
            return msg_printer.show_msg(MsgType::UnknownOption(option));
        }
    }
    Ok(())
}

fn print_file_size(file_path: &str, human_readable: bool) -> Result<(), String> {
    unsafe {
        let fp = libc::fopen(string_to_c_str(file_path), str_to_c_str("rb"));
        if fp.is_null() {
            return Err(String::from("Failed to open file"));
        }
        if portable_fseek(fp, 0, libc::SEEK_END) != 0 {
            return Err(String::from("Failed to seek file"));
        }
        let size = portable_ftell(fp);
        if size < 0 {
            return Err(format!("ftell error, errno: {}", errno::errno().0));
        }
        let size = size as u64;
        if human_readable {
            let size = SizeFormatterBinary::new(size).to_string();
            println!("{}B", size);
        } else {
            println!("{}", size);
        }
        Ok(())
    }
}

fn str_to_c_str(s: &str) -> *const libc::c_char {
    return s.as_bytes().as_ptr() as *const libc::c_char;
}

fn string_to_c_str(s: &str) -> *const libc::c_char {
    str_to_c_str(s)
}

#[cfg(target_family = "windows")]
fn portable_ftell(fp: *mut libc::FILE) -> libc::off_t {
    unsafe { libc::ftell(fp) }
}

#[cfg(target_family = "windows")]
fn portable_fseek(fp: *mut libc::FILE, offset: libc::c_long, whence: libc::c_int) -> libc::c_int {
    unsafe { libc::fseek(fp, offset, whence) }
}

#[cfg(target_family = "unix")]
fn portable_ftell(fp: *mut libc::FILE) -> libc::off_t {
    unsafe { libc::ftello(fp) }
}

#[cfg(target_family = "unix")]
fn portable_fseek(fp: *mut libc::FILE, offset: libc::c_long, whence: libc::c_int) -> libc::c_int {
    unsafe { libc::fseeko(fp, offset, whence) }
}

struct Arguments {
    human_readable: bool,
}