Skip to content

Commit bf9f850

Browse files
committed
speedup base_n::push_str
1 parent 72868e0 commit bf9f850

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

compiler/rustc_data_structures/src/base_n.rs

+8-7
Original file line numberDiff line numberDiff line change
@@ -14,24 +14,25 @@ const BASE_64: &[u8; MAX_BASE as usize] =
1414

1515
#[inline]
1616
pub fn push_str(mut n: u128, base: usize, output: &mut String) {
17-
debug_assert!(base >= 2 && base <= MAX_BASE);
17+
assert!(base >= 2 && base <= MAX_BASE);
1818
let mut s = [0u8; 128];
19-
let mut index = 0;
19+
let mut first_index = 0;
2020

2121
let base = base as u128;
2222

23-
loop {
24-
s[index] = BASE_64[(n % base) as usize];
25-
index += 1;
23+
for idx in (0..128).rev() {
24+
// SAFETY: given `base <= MAX_BASE`, so `n % base < MAX_BASE`
25+
s[idx] = unsafe { *BASE_64.get_unchecked((n % base) as usize) };
2626
n /= base;
2727

2828
if n == 0 {
29+
first_index = idx;
2930
break;
3031
}
3132
}
32-
s[0..index].reverse();
3333

34-
output.push_str(str::from_utf8(&s[0..index]).unwrap());
34+
// SAFETY: all chars in given range is nonnull ascii
35+
output.push_str(unsafe { str::from_utf8_unchecked(&s[first_index..]) });
3536
}
3637

3738
#[inline]

0 commit comments

Comments
 (0)