From 7b33d39da93a9873fa002c6875c934fd13ec7d4a Mon Sep 17 00:00:00 2001 From: Andrea Canciani Date: Wed, 30 Dec 2015 22:03:35 +0100 Subject: [PATCH] Improve computation of `EscapeUnicode` offset field Instead of iteratively scanning the bits, use `leading_zeros`. --- src/libcore/char.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/libcore/char.rs b/src/libcore/char.rs index df6044fa8392..1df2d0d3bc8c 100644 --- a/src/libcore/char.rs +++ b/src/libcore/char.rs @@ -299,14 +299,16 @@ impl CharExt for char { #[inline] fn escape_unicode(self) -> EscapeUnicode { - let mut n = 0; - while (self as u32) >> (4 * (n + 1)) != 0 { - n += 1; - } + let c = self as u32; + // or-ing 1 ensures that for c==0 the code computes that one + // digit should be printed and (which is the same) avoids the + // (31 - 32) underflow + let msb = 31 - (c | 1).leading_zeros(); + let msdigit = msb / 4; EscapeUnicode { c: self, state: EscapeUnicodeState::Backslash, - offset: n, + offset: msdigit as usize, } }