kutil_std/metric/
units.rs

1use super::super::string::*;
2
3/// Kilo.
4pub const KILO: u64 = 1000;
5
6/// Mega.
7pub const MEGA: u64 = 1000 * 1000;
8
9/// Giga.
10pub const GIGA: u64 = 1000 * 1000 * 1000;
11
12/// Tera.
13pub const TERA: u64 = 1000 * 1000 * 1000 * 1000;
14
15/// Kibi.
16pub const KIBI: u64 = 1024;
17
18/// Mebi.
19pub const MEBI: u64 = 1024 * 1024;
20
21/// Gibi.
22pub const GIBI: u64 = 1024 * 1024 * 1024;
23
24/// Tebi.
25pub const TEBI: u64 = 1024 * 1024 * 1024 * 1024;
26
27/// Parse unit.
28pub fn parse_metric_unit(representation: &str) -> Result<u64, ParseError> {
29    match representation.to_lowercase().as_str() {
30        "" | "b" | "byte" | "bytes" => Ok(1),
31        "kb" | "kilobyte" | "kilobytes" => Ok(KILO),
32        "mb" | "megabyte" | "megabytes" => Ok(MEGA),
33        "gb" | "gigabyte" | "gigabytes" => Ok(GIGA),
34        "tb" | "terabyte" | "terabytes" => Ok(TERA),
35        "kib" | "kibibyte" | "kibibytes" => Ok(KIBI),
36        "mib" | "mebibyte" | "mebibytes" => Ok(MEBI),
37        "gib" | "gibibyte" | "gibibytes" => Ok(GIBI),
38        "tib" | "tebibyte" | "tebibytes" => Ok(TEBI),
39        _ => return Err(format!("unsupported unit: {}", representation).into()),
40    }
41}