Skip to content

Commit c6d2bb7

Browse files
committed
improve codegen of fmt_num to delete unreachable panic
it seems LLVM doesn't realize that `curr` is always decremented at least once in either loop formatting characters of the input string by their appropriate radix, and so the later `&buf[curr..]` generates a check for out-of-bounds access and panic. this is unreachable in reality as even for `x == T::zero()` we'll produce at least the character `Self::digit(T::zero())` for at least one character output, and `curr` will always be at least one below `buf.len()`. adjust `fmt_int` to make this fact more obvious to the compiler, which fortunately (or unfortunately) results in a measurable performance improvement for workloads heavy on formatting integers.
1 parent 66b9f79 commit c6d2bb7

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

core/src/fmt/num.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -79,23 +79,23 @@ unsafe trait GenericRadix: Sized {
7979
if is_nonnegative {
8080
// Accumulate each digit of the number from the least significant
8181
// to the most significant figure.
82-
for byte in buf.iter_mut().rev() {
82+
loop {
8383
let n = x % base; // Get the current place value.
8484
x = x / base; // Deaccumulate the number.
85-
byte.write(Self::digit(n.to_u8())); // Store the digit in the buffer.
8685
curr -= 1;
86+
buf[curr].write(Self::digit(n.to_u8())); // Store the digit in the buffer.
8787
if x == zero {
8888
// No more digits left to accumulate.
8989
break;
9090
};
9191
}
9292
} else {
9393
// Do the same as above, but accounting for two's complement.
94-
for byte in buf.iter_mut().rev() {
94+
loop {
9595
let n = zero - (x % base); // Get the current place value.
9696
x = x / base; // Deaccumulate the number.
97-
byte.write(Self::digit(n.to_u8())); // Store the digit in the buffer.
9897
curr -= 1;
98+
buf[curr].write(Self::digit(n.to_u8())); // Store the digit in the buffer.
9999
if x == zero {
100100
// No more digits left to accumulate.
101101
break;

0 commit comments

Comments
 (0)