Skip to content

Commit 7b33d39

Browse files
committed
Improve computation of EscapeUnicode offset field
Instead of iteratively scanning the bits, use `leading_zeros`.
1 parent 2fd2670 commit 7b33d39

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

src/libcore/char.rs

+7-5
Original file line numberDiff line numberDiff line change
@@ -299,14 +299,16 @@ impl CharExt for char {
299299

300300
#[inline]
301301
fn escape_unicode(self) -> EscapeUnicode {
302-
let mut n = 0;
303-
while (self as u32) >> (4 * (n + 1)) != 0 {
304-
n += 1;
305-
}
302+
let c = self as u32;
303+
// or-ing 1 ensures that for c==0 the code computes that one
304+
// digit should be printed and (which is the same) avoids the
305+
// (31 - 32) underflow
306+
let msb = 31 - (c | 1).leading_zeros();
307+
let msdigit = msb / 4;
306308
EscapeUnicode {
307309
c: self,
308310
state: EscapeUnicodeState::Backslash,
309-
offset: n,
311+
offset: msdigit as usize,
310312
}
311313
}
312314

0 commit comments

Comments
 (0)