Skip to content

Commit ecef52a

Browse files
committed
Auto merge of #86304 - klensy:hex-length, r=jackh726
rustc_mir: calc hex number length without string allocation
2 parents 64de497 + 2b57fc4 commit ecef52a

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
@@ -819,7 +819,7 @@ fn write_allocation_bytes<Tag: Copy + Debug, Extra>(
819819
) -> std::fmt::Result {
820820
let num_lines = alloc.size().bytes_usize().saturating_sub(BYTES_PER_LINE);
821821
// Number of chars needed to represent all line numbers.
822-
let pos_width = format!("{:x}", alloc.size().bytes()).len();
822+
let pos_width = hex_number_length(alloc.size().bytes());
823823

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

0 commit comments

Comments
 (0)