Skip to content

Commit 2b57fc4

Browse files
committed
rustc_mir: calc hex number length without string allocation
1 parent a216131 commit 2b57fc4

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

compiler/rustc_mir/src/util/pretty.rs

+21-1
Original file line numberDiff line numberDiff line change
@@ -824,7 +824,7 @@ fn write_allocation_bytes<Tag: Copy + Debug, Extra>(
824824
) -> std::fmt::Result {
825825
let num_lines = alloc.size().bytes_usize().saturating_sub(BYTES_PER_LINE);
826826
// Number of chars needed to represent all line numbers.
827-
let pos_width = format!("{:x}", alloc.size().bytes()).len();
827+
let pos_width = hex_number_length(alloc.size().bytes());
828828

829829
if num_lines > 0 {
830830
write!(w, "{}0x{:02$x} │ ", prefix, 0, pos_width)?;
@@ -1023,3 +1023,23 @@ pub fn dump_mir_def_ids(tcx: TyCtxt<'_>, single: Option<DefId>) -> Vec<DefId> {
10231023
tcx.mir_keys(()).iter().map(|def_id| def_id.to_def_id()).collect()
10241024
}
10251025
}
1026+
1027+
/// Calc converted u64 decimal into hex and return it's length in chars
1028+
///
1029+
/// ```ignore (cannot-test-private-function)
1030+
/// assert_eq!(1, hex_number_length(0));
1031+
/// assert_eq!(1, hex_number_length(1));
1032+
/// assert_eq!(2, hex_number_length(16));
1033+
/// ```
1034+
fn hex_number_length(x: u64) -> usize {
1035+
if x == 0 {
1036+
return 1;
1037+
}
1038+
let mut length = 0;
1039+
let mut x_left = x;
1040+
while x_left > 0 {
1041+
x_left /= 16;
1042+
length += 1;
1043+
}
1044+
length
1045+
}

0 commit comments

Comments
 (0)