implement format_bytes as usize trait

This commit is contained in:
yggverse 2025-01-28 17:22:37 +02:00
parent 8ea11a215a
commit 6f814dd382
2 changed files with 23 additions and 20 deletions

View file

@ -1,23 +1,26 @@
//! Some shared helpers collection
/// Format bytes to KB/MB/GB presentation
pub fn format_bytes(value: usize) -> String {
const KB: f32 = 1024.0;
const MB: f32 = KB * KB;
const GB: f32 = MB * KB;
pub trait Format {
/// Format bytes to KB/MB/GB presentation
fn bytes(&self) -> String;
}
let f = value as f32;
impl Format for usize {
fn bytes(&self) -> String {
const KB: f32 = 1024.0;
const MB: f32 = KB * KB;
const GB: f32 = MB * KB;
if f < KB {
format!(
"{value} {}",
plurify::ns(value, &["byte", "bytes", "bytes"])
)
} else if f < MB {
format!("{:.2} KB", f / KB)
} else if f < GB {
format!("{:.2} MB", f / MB)
} else {
format!("{:.2} GB", f / GB)
let f = *self as f32;
if f < KB {
format!("{self} {}", plurify::ns(*self, &["byte", "bytes", "bytes"]))
} else if f < MB {
format!("{:.2} KB", f / KB)
} else if f < GB {
format!("{:.2} MB", f / MB)
} else {
format!("{:.2} GB", f / GB)
}
}
}