backblaze_b2_client/util/
size_unit.rs

1use std::fmt::Display;
2
3#[derive(Debug, Clone)]
4pub enum SizeUnit {
5    KibiByte(f64),
6    MebiByte(f64),
7    GibiByte(f64),
8}
9
10impl SizeUnit {
11    pub const KIBIBYTE: u64 = 1024;
12    pub const MEBIBYTE: u64 = 1024 * SizeUnit::KIBIBYTE;
13    pub const GIBIBYTE: u64 = 1024 * SizeUnit::MEBIBYTE;
14
15    /// Returns current represented value as bytes
16    pub fn as_bytes(self) -> f64 {
17        match self {
18            Self::KibiByte(v) => v * SizeUnit::KIBIBYTE as f64,
19            Self::MebiByte(v) => v * SizeUnit::MEBIBYTE as f64,
20            Self::GibiByte(v) => v * SizeUnit::GIBIBYTE as f64,
21        }
22    }
23}
24
25impl<T: Into<f64>> From<T> for SizeUnit {
26    fn from(value: T) -> Self {
27        let value = value.into();
28
29        if value > Self::GIBIBYTE as f64 {
30            SizeUnit::GibiByte(value / SizeUnit::GIBIBYTE as f64)
31        } else if value > Self::MEBIBYTE as f64 {
32            SizeUnit::MebiByte(value / SizeUnit::MEBIBYTE as f64)
33        } else {
34            SizeUnit::KibiByte(value / SizeUnit::KIBIBYTE as f64)
35        }
36    }
37}
38
39impl Display for SizeUnit {
40    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41        let (value, type_str) = match *self {
42            Self::KibiByte(v) => (v, "KiB"),
43            Self::MebiByte(v) => (v, "MiB"),
44            Self::GibiByte(v) => (v, "GiB"),
45        };
46
47        match f.precision() {
48            Some(precision) => f.write_fmt(format_args!(
49                "{:.precision$} {}",
50                value,
51                type_str,
52                precision = precision
53            )),
54            None => f.write_fmt(format_args!("{} {}", value, type_str)),
55        }
56    }
57}