Skip to content

Commit

Permalink
Avoid allocating strings when formatting bytes
Browse files Browse the repository at this point in the history
  • Loading branch information
nical committed Jul 18, 2024
1 parent a1aee6d commit 3d6b3a2
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 17 deletions.
30 changes: 16 additions & 14 deletions src/allocator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ impl fmt::Debug for AllocationReport {
} else {
"--"
};
write!(f, "{name:?}: {}", fmt_bytes(self.size))
write!(f, "{name:?}: {}", FmtBytes(self.size))
}
}

Expand All @@ -89,8 +89,8 @@ impl fmt::Debug for AllocatorReport {
"summary",
&std::format_args!(
"{} / {}",
fmt_bytes(self.total_allocated_bytes),
fmt_bytes(self.total_reserved_bytes)
FmtBytes(self.total_allocated_bytes),
FmtBytes(self.total_reserved_bytes)
),
)
.field("blocks", &self.blocks.len())
Expand Down Expand Up @@ -145,18 +145,20 @@ pub(crate) trait SubAllocator: SubAllocatorBase + fmt::Debug + Sync + Send {
}
}

pub(crate) fn fmt_bytes(mut amount: u64) -> String {
const SUFFIX: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
pub struct FmtBytes(pub u64);

let mut idx = 0;
let mut print_amount = amount as f64;
loop {
if amount < 1024 {
return format!("{:.2} {}", print_amount, SUFFIX[idx]);
impl fmt::Display for FmtBytes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
const SUFFIX: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
let mut idx = 0;
let mut amount = self.0 as f64;
loop {
if amount < 1024.0 || idx == SUFFIX.len() - 1 {
return write!(f, "{:.2} {}", amount, SUFFIX[idx]);
}

amount /= 1024.0;
idx += 1;
}

print_amount = amount as f64 / 1024.0;
amount /= 1024;
idx += 1;
}
}
6 changes: 3 additions & 3 deletions src/visualizer/allocation_reports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::backtrace::BacktraceStatus;
use egui::{Label, Response, Sense, Ui, WidgetText};
use egui_extras::{Column, TableBuilder};

use crate::allocator::{fmt_bytes, AllocationReport};
use crate::allocator::{FmtBytes, AllocationReport};

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum AllocationReportVisualizeSorting {
Expand Down Expand Up @@ -39,7 +39,7 @@ pub(crate) fn render_allocation_reports_ui(
.collect::<Vec<_>>();
let total_size_under_filter: u64 = allocations.iter().map(|a| a.1.size).sum();

ui.label(format!("Total: {}", fmt_bytes(total_size_under_filter)));
ui.label(format!("Total: {}", FmtBytes(total_size_under_filter)));

let row_height = ui.text_style_height(&egui::TextStyle::Body);
let table = TableBuilder::new(ui)
Expand Down Expand Up @@ -133,7 +133,7 @@ pub(crate) fn render_allocation_reports_ui(
}

row.col(|ui| {
ui.label(fmt_bytes(size));
ui.label(format!("{}", FmtBytes(size)));
});
});
}
Expand Down

0 comments on commit 3d6b3a2

Please sign in to comment.