41 lines
1.2 KiB
Rust
41 lines
1.2 KiB
Rust
use std::fmt;
|
|
|
|
const KILOS: f64 = 1024.0;
|
|
const MEGAS: f64 = KILOS * 1024.0;
|
|
const GIGAS: f64 = MEGAS * 1024.0;
|
|
const TERAS: f64 = GIGAS * 1024.0;
|
|
|
|
#[derive(Clone, Copy, Debug)]
|
|
pub enum HumanSize {
|
|
Bytes(u64),
|
|
KiloBytes(f64),
|
|
MegaBytes(f64),
|
|
GigaBytes(f64),
|
|
TeraBytes(f64),
|
|
}
|
|
|
|
impl fmt::Display for HumanSize {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
match self {
|
|
Self::Bytes(b) => write!(f, "{b:>7}"),
|
|
Self::KiloBytes(k) => write!(f, "{k:>6.1}K"),
|
|
Self::MegaBytes(m) => write!(f, "{m:>6.1}M"),
|
|
Self::GigaBytes(g) => write!(f, "{g:>6.1}G"),
|
|
Self::TeraBytes(t) => write!(f, "{t:>6.1}T"),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[allow(clippy::cast_precision_loss)]
|
|
impl From<u64> for HumanSize {
|
|
fn from(value: u64) -> Self {
|
|
match value {
|
|
n if n as f64 > TERAS => Self::GigaBytes(n as f64 / TERAS),
|
|
n if n as f64 > GIGAS => Self::GigaBytes(n as f64 / GIGAS),
|
|
n if n as f64 > MEGAS => Self::MegaBytes(n as f64 / MEGAS),
|
|
n if n as f64 > KILOS => Self::KiloBytes(n as f64 / KILOS),
|
|
_ => Self::Bytes(value),
|
|
}
|
|
}
|
|
}
|