Skip to content

Commit

Permalink
improve codegen of fmt_num to delete unreachable panic
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
iximeow committed Mar 20, 2024
1 parent 66b9f79 commit c6d2bb7
Showing 1 changed file with 4 additions and 4 deletions.
8 changes: 4 additions & 4 deletions core/src/fmt/num.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,23 +79,23 @@ unsafe trait GenericRadix: Sized {
if is_nonnegative {
// Accumulate each digit of the number from the least significant
// to the most significant figure.
for byte in buf.iter_mut().rev() {
loop {
let n = x % base; // Get the current place value.
x = x / base; // Deaccumulate the number.
byte.write(Self::digit(n.to_u8())); // Store the digit in the buffer.
curr -= 1;
buf[curr].write(Self::digit(n.to_u8())); // Store the digit in the buffer.
if x == zero {
// No more digits left to accumulate.
break;
};
}
} else {
// Do the same as above, but accounting for two's complement.
for byte in buf.iter_mut().rev() {
loop {
let n = zero - (x % base); // Get the current place value.
x = x / base; // Deaccumulate the number.
byte.write(Self::digit(n.to_u8())); // Store the digit in the buffer.
curr -= 1;
buf[curr].write(Self::digit(n.to_u8())); // Store the digit in the buffer.
if x == zero {
// No more digits left to accumulate.
break;
Expand Down

0 comments on commit c6d2bb7

Please sign in to comment.