Skip to content

rustc_mir: calc hex number length without string allocation #86304

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 1, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion compiler/rustc_mir/src/util/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -824,7 +824,7 @@ fn write_allocation_bytes<Tag: Copy + Debug, Extra>(
) -> std::fmt::Result {
let num_lines = alloc.size().bytes_usize().saturating_sub(BYTES_PER_LINE);
// Number of chars needed to represent all line numbers.
let pos_width = format!("{:x}", alloc.size().bytes()).len();
let pos_width = hex_number_length(alloc.size().bytes());

if num_lines > 0 {
write!(w, "{}0x{:02$x} │ ", prefix, 0, pos_width)?;
Expand Down Expand Up @@ -1023,3 +1023,23 @@ pub fn dump_mir_def_ids(tcx: TyCtxt<'_>, single: Option<DefId>) -> Vec<DefId> {
tcx.mir_keys(()).iter().map(|def_id| def_id.to_def_id()).collect()
}
}

/// Calc converted u64 decimal into hex and return it's length in chars
///
/// ```ignore (cannot-test-private-function)
/// assert_eq!(1, hex_number_length(0));
/// assert_eq!(1, hex_number_length(1));
/// assert_eq!(2, hex_number_length(16));
/// ```
fn hex_number_length(x: u64) -> usize {
if x == 0 {
return 1;
}
let mut length = 0;
let mut x_left = x;
while x_left > 0 {
x_left /= 16;
length += 1;
}
length
}