Debian Codegraph @

src/utils/conversion.rs

raw symbols SCIP
1 //! This mainly concerns converting collected data into things that the canvas
2 //! can actually handle.
3
4 use crate::utils::data_units::*;
5
6 /// Returns the most appropriate binary prefix unit type (e.g. kibibyte) and
7 /// denominator for the given amount of bytes.
8 ///
9 /// The expected usage is to divide out the given value with the returned
10 /// denominator in order to be able to use it with the returned binary unit
11 /// (e.g. divide 3000 bytes by 1024 to have a value in KiB).
12 #[inline]
13 pub(crate) fn get_binary_unit_and_denominator(bytes: u64) -> (&'static str, f64) {
14 match bytes {
15 b if b < KIBI_LIMIT => ("B", 1.0),
16 b if b < MEBI_LIMIT => ("KiB", KIBI_LIMIT_F64),
17 b if b < GIBI_LIMIT => ("MiB", MEBI_LIMIT_F64),
18 b if b < TEBI_LIMIT => ("GiB", GIBI_LIMIT_F64),
19 _ => ("TiB", TEBI_LIMIT_F64),
20 }
21 }
22
23 /// Returns a string given a value that is converted to the closest SI-variant,
24 /// per second. If the value is greater than a giga-X, then it will return a
25 /// decimal place.
26 #[inline]
27 pub(crate) fn dec_bytes_per_second_string(value: u64) -> String {
28 let converted_values = get_decimal_bytes(value);
29 if value >= GIGA_LIMIT {
30 format!("{:.1}{}/s", converted_values.0, converted_values.1)
31 } else {
32 format!("{:.0}{}/s", converted_values.0, converted_values.1)
33 }
34 }
35
36 #[cfg(test)]
37 mod test {
38 use super::*;
39
40 #[test]
41 fn test_dec_bytes_per_second_string() {
42 assert_eq!(dec_bytes_per_second_string(0), "0B/s".to_string());
43 assert_eq!(dec_bytes_per_second_string(1), "1B/s".to_string());
44 assert_eq!(dec_bytes_per_second_string(900), "900B/s".to_string());
45 assert_eq!(dec_bytes_per_second_string(999), "999B/s".to_string());
46 assert_eq!(dec_bytes_per_second_string(KILO_LIMIT), "1KB/s".to_string());
47 assert_eq!(
48 dec_bytes_per_second_string(KILO_LIMIT + 1),
49 "1KB/s".to_string()
50 );
51 assert_eq!(dec_bytes_per_second_string(KIBI_LIMIT), "1KB/s".to_string());
52 assert_eq!(dec_bytes_per_second_string(MEGA_LIMIT), "1MB/s".to_string());
53 assert_eq!(
54 dec_bytes_per_second_string(GIGA_LIMIT),
55 "1.0GB/s".to_string()
56 );
57 assert_eq!(
58 dec_bytes_per_second_string(2 * GIGA_LIMIT),
59 "2.0GB/s".to_string()
60 );
61 assert_eq!(
62 dec_bytes_per_second_string((2.5 * GIGA_LIMIT as f64) as u64),
63 "2.5GB/s".to_string()
64 );
65 assert_eq!(
66 dec_bytes_per_second_string((10.34 * TERA_LIMIT as f64) as u64),
67 "10.3TB/s".to_string()
68 );
69 assert_eq!(
70 dec_bytes_per_second_string((10.36 * TERA_LIMIT as f64) as u64),
71 "10.4TB/s".to_string()
72 );
73 }
74 }