Skip to content

Commit 0588a06

Browse files
committed
Avoid allocating strings when formatting allocation sizes
1 parent a1aee6d commit 0588a06

File tree

2 files changed

+19
-17
lines changed

2 files changed

+19
-17
lines changed

src/allocator/mod.rs

+16-14
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ impl fmt::Debug for AllocationReport {
7272
} else {
7373
"--"
7474
};
75-
write!(f, "{name:?}: {}", fmt_bytes(self.size))
75+
write!(f, "{name:?}: {}", FmtBytes(self.size))
7676
}
7777
}
7878

@@ -89,8 +89,8 @@ impl fmt::Debug for AllocatorReport {
8989
"summary",
9090
&std::format_args!(
9191
"{} / {}",
92-
fmt_bytes(self.total_allocated_bytes),
93-
fmt_bytes(self.total_reserved_bytes)
92+
FmtBytes(self.total_allocated_bytes),
93+
FmtBytes(self.total_reserved_bytes)
9494
),
9595
)
9696
.field("blocks", &self.blocks.len())
@@ -145,18 +145,20 @@ pub(crate) trait SubAllocator: SubAllocatorBase + fmt::Debug + Sync + Send {
145145
}
146146
}
147147

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

151-
let mut idx = 0;
152-
let mut print_amount = amount as f64;
153-
loop {
154-
if amount < 1024 {
155-
return format!("{:.2} {}", print_amount, SUFFIX[idx]);
150+
impl fmt::Display for FmtBytes {
151+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152+
const SUFFIX: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
153+
let mut idx = 0;
154+
let mut amount = self.0 as f64;
155+
loop {
156+
if amount < 1024.0 || idx >= SUFFIX.len() - 1 {
157+
return write!(f, "{:.2} {}", amount, SUFFIX[idx]);
158+
}
159+
160+
amount /= 1024.0;
161+
idx += 1;
156162
}
157-
158-
print_amount = amount as f64 / 1024.0;
159-
amount /= 1024;
160-
idx += 1;
161163
}
162164
}

src/visualizer/allocation_reports.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use std::backtrace::BacktraceStatus;
33
use egui::{Label, Response, Sense, Ui, WidgetText};
44
use egui_extras::{Column, TableBuilder};
55

6-
use crate::allocator::{fmt_bytes, AllocationReport};
6+
use crate::allocator::{AllocationReport, FmtBytes};
77

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

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

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

135135
row.col(|ui| {
136-
ui.label(fmt_bytes(size));
136+
ui.label(format!("{}", FmtBytes(size)));
137137
});
138138
});
139139
}

0 commit comments

Comments
 (0)